package com.springcloud.demo.zuulGateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public boolean shouldFilter() {
        return true;//该过滤器是否执行
    }

    /**
     * 返回字符串代表过滤器的类型
     *
     * pre:请求在被路由之前执行
     * routing:在路由请求时调用
     * post:在routing和error之后调用
     * error:处理请求时发生错误调用
     *
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;//过滤器执行顺序
    }

    /**
     * 过滤器业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        //拿到当前请求
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            requestContext.setSendZuulResponse(false);// zuul过滤器 过滤掉该请求，不对其进行路由
            requestContext.setResponseStatusCode(401);// 设置响应状态码
            return  null;
        }

        return null;
    }
}
